<template>
    <div class="work">
        <!-- v-if="!isShow" -->
        <div>
            <div class="work-tit">
                <p class="person-infro">我的工单</p>
                <el-button class="btn" type="primary" icon="el-icon-plus" @click="getAdd">新增</el-button>
            </div>
            <el-divider></el-divider>
            <el-table
                :data="tableData"
                style="width: 100%"
                :header-cell-style="{background:'rgba(0,0,0,0.06)'}"
                >
                <el-table-column
                    align="center"
                    prop="id"
                    label="序列号"
                    class-name="titleClass"
                    width="150">
                    <template slot-scope="scope">
                        <p class="title">{{scope.row.id}}</p>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="priorityName"
                    label="优先级"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="topic"
                    label="主题"
                    class-name="titleClass"
                    >
                    <template slot-scope="scope">
                        <p class="title" @click="handleDetail(scope.$index, scope.row)">{{scope.row.topic}}</p>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    width="150"
                    label="创建时间">
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageParams.pageNo"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageParams.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <!-- 新增 -->
        <el-dialog :visible.sync="addTableVisible" class="addOrder">
            <div class="work-tit">
                <p class="person-back" @click="getbackAdd"><i class="el-icon-arrow-left"></i>返回上一页</p>
                <p></p>
            </div>
            <el-divider></el-divider>
            <el-form :model="orderForm" :rules="rules" ref="orderForm" class="fromClass">
                <el-form-item label="主题" :label-width="formLabelWidth" prop="topic">
                    <el-input v-model.trim="orderForm.topic"></el-input>
                </el-form-item>
                <el-form-item label="描述" :label-width="formLabelWidth">
                    <richTxt ref="child" v-model="orderForm.describe" @change="changeTxt"/>
                </el-form-item>
                <el-form-item label="优先级" :label-width="formLabelWidth" prop="priority">
                    <el-select v-model="orderForm.priority">
                        <el-option v-for="(item,index) in priorityOption" :key="index" :label="item.name" :value="item.avdRelId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="类别" :label-width="formLabelWidth" prop="typeId">
                    <el-cascader v-model="orderForm.typeId" :options="options" @change="handleTypeChange" :props="defaultParams"></el-cascader>
                </el-form-item>
                <el-form-item label="上传文件" :label-width="formLabelWidth">
                    <el-upload
                        class="upload-demo"
                        :action="upload_file_url"
                        multiple
                        :limit="5"
                        :headers="upHeaders"
                        :before-upload="beforeAvatarUpload"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :on-exceed="handleExceed"
                        >
                        <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                </el-form-item>
                <el-form-item class="btn-box">
                    <el-button class="concal" @click="addTableVisible=false">取消</el-button>
                    <el-button type="primary" @click="onSubmit('orderForm')">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog :visible.sync="dialogTableVisible">
            <p class="topic">{{articleObj.topic}}</p>
            <div class="priority">
                <p>优先级：</p>
                <p class="priority-name">{{acticleInfo.priorityName}}</p>
                <p>指派给：</p>
                <p class="priority-name sed-name">{{acticleInfo.headUser}}</p>
            </div>
            <el-divider></el-divider>
            <p class="tips">描述</p>
            <div v-if="acticleInfo.describe" class="descrip-tit" v-html="acticleInfo.describe"></div>
            <el-empty :image-size="80"  v-else></el-empty>
            <el-divider></el-divider>
            <p class="tips">文件</p>
            <ul class="file-upload" v-if="acticleInfofile.length != 0">
                <li class="watchFile" v-for="(item,index) in acticleInfofile" :key="index">
                    <div>
                        <i class="el-icon-document fileSize"></i>
                        <el-link :underline="false" type="primary" @click="goHref(item.filePath)">{{item.fileName}}</el-link>
                        <p>({{item.fileSize | filterType}})</p>
                        <i class="el-icon-download unloadSize" @click="getLoad(item.id,item.fileName)"></i>
                    </div>
                    <div>
                        <p>{{item.createUserName}}，</p>
                        <p>{{item.createTime}}</p>
                        <i class="el-icon-delete delSize" @click="deleteOrder(item.id)"></i>
                    </div>
                </li>
            </ul>
            <!-- <div v-else>暂无数据</div> -->
            <el-empty :image-size="80"  v-else></el-empty>
            <el-divider></el-divider>
            <p class="tips">历史记录</p>
            <div class="history-box">
                <ol class="history">
                    <li v-for="(item,index) in acticleInfo.recordList" :key="index">
                        <p>{{item.record}}</p>
                        <p v-html="item.describe"></p>
                        <div v-if="item.fileList">
                            <div class="watchFile" v-for="(val,key) in item.fileList" :key="key">
                                <div>
                                <i class="el-icon-document fileSize"></i>
                                <el-link :underline="false" type="primary" @click="goHref(val.filePath)">{{val.fileName}}</el-link>
                                <p>({{val.fileSize | filterType}})</p>
                                <i class="el-icon-download unloadSize" @click="getLoad(val.id,val.fileName)"></i>
                            </div>
                            <div>
                                <p>{{val.createUserName}}，</p>
                                <p>{{val.createTime}}</p>
                                <i class="el-icon-delete delSize" @click="deleteRecordOrder(val.id)"></i>
                            </div>
                            </div>
                        </div>
                    </li>
                </ol>
            </div>
            
            <!-- <el-input type="textarea" v-model="descrision"></el-input> -->
            <el-button class="sumbit" type="primary" @click="getAnswer(articleObj.id)">回复</el-button>
        </el-dialog>
        <el-dialog
            width="50%"
            :visible.sync="innerVisible"
            title="回复"
            append-to-body>
            <el-form ref="formData" :model="replyParams">
                <el-form-item prop="describe">
                    <richTxt ref="child" class="txt-box" v-model="replyParams.describe" @change="changeReplyTxt"/>
                </el-form-item>
                <el-form-item prop="fileUrls">
                    <el-upload class="upload-demo" ref="uploadFile" :action="upload_file_url" :headers="upHeaders" multiple :limit="5" :before-upload="beforeReplyAvatarUpload" :on-remove="handleReplyRemove"
                        :on-success="handleReplySuccess"
                        :on-exceed="handleReplyExceed">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <el-button class="sumbit" type="primary" @click="getBtn('formData')">确定</el-button>
                
        </el-dialog>
    </div>
</template>
<script>
import richTxt from './RichText.vue';
import {repairOrderList,addRepairOrder,replyRepairOrder,queryRepairOrderType,repairOrderInfo,deleteRepairOrder,downloadRepairOrder,deleteByFilePath} from './../api/user'
export default {
    components: { richTxt },
    filters:{
        filterType:function(val){
            if(val === null){
                return '0 B'
            }
            const size = 1024;
            const unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
            let i = Math.floor(Math.log(val) / Math.log(size));
            return (val / Math.pow(size,i)).toPrecision(3) + "" + unit[i]
        }
    },
    data(){
        return{
            tableData: [],
            total:0,
            isShow:false,
            upload_file_url: process.env.VUE_APP_URL + '/api/v1/file/uploadImage?category=fileList',
            upHeaders:{
                'Authorization':"6a77998089b8467d83d2094a8011b02d"
            },
            orderForm:{
                topic:"",
                describe:'',
                priority:'',
                typeId:"",
                fileUrls:[],
            },
            priorityOption:[{
                avdRelId: 1,
                name: '普通'
            },{
                avdRelId: 2,
                name: '低'
            },{
                avdRelId:3,
                name: '高'
            },{
                avdRelId: 4,
                name: '紧急'
            },{
                avdRelId: 5,
                name: '立刻'
            }],
            options:[],
            defaultParams:{
                label:'className',
                value:'id',
                children:'children',
                checkStrictly: true,
            },
            rules:{
                topic:[
                    {required:true, message: '请输入主题', trigger: 'blur'}
                ],
                priority:[
                    {required:true, message: '请选择优先级', trigger: 'blur'},
                ],
                typeId:[
                    {required:true, message: '请选择类别', trigger: 'blur'},
                ],
            },
            formLabelWidth: '120px',
            dialogTableVisible:false,
            addTableVisible:false,
            innerVisible:false,
            articleObj:{},
            acticleInfo:{},
            acticleInfofile:[],
            replyParams:{
                describe:"",
                fileUrls:[],
                id:"",
            },
            pageParams:{
                pageNo:1,
                pageSize:20,
            },

            
        }
    },
    methods:{
        // 点击新增
        getAdd(){
            this.addTableVisible = true;
        },
        getbackAdd(){
            this.addTableVisible = false;
        },
        handleDetail(index,row){
            console.log(index,row);
            this.articleObj = row;
            repairOrderInfo(this.articleObj.id).then(res=>{
                if(res.code == 200){
                    this.acticleInfo = res.result;
                    console.log(this.acticleInfo,'内容');
                    this.acticleInfofile = this.acticleInfo.fileList;

                }
            })
            this.dialogTableVisible = true;
        },
        // 工单列表
        repairOrderList(){
            repairOrderList(this.pageParams.pageNo,this.pageParams.pageSize).then(res=>{
                if(res.code == 200){
                    this.tableData = res.result.data;
                    this.total = res.result.count;
                }
            })
        },
        // 分页
        handleSizeChange(val) {
            this.pageParams.pageSize = val;
        },
        handleCurrentChange(val) {
            this.pageParams.pageNo = val;
            console.log(this.pageParams.pageNo);
        },
        // 跳转文本
        goHref(url){
            window.open(url);
        },
        // 新增工单富文本
        changeTxt(data){
            this.orderForm.describe = data;
        },
        // 工单类别
        repairOrderType(){
            queryRepairOrderType().then(res=>{
                this.options = res.result;
                
            })
        },
        handleTypeChange(value){
                let arrCopy = value.concat();
                this.orderForm.typeId = arrCopy.pop();
        },
        // 上传文件尺寸
        beforeAvatarUpload(file){
            console.log(file);
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!isLt5M) {
                this.$message.error('上传文件大小不能超过 5MB!');
            }
            return isLt5M;
        },
        // 文件上传超出限制
        handleExceed(files, fileList){
            this.$message.warning('不能超过5个文件上传')
        },
        // 上传文件删除
        handleRemove(file, fileList){
            console.log(file, fileList);
            this.orderForm.fileUrls.forEach((item,index) => {
                if(file.response.result.absoluteUrl == item.url){
                    let params = {
                        filePath: item.url
                    }
                    deleteByFilePath(params).then(res=>{
                        if(res.code==200){
                            this.$message.success("删除成功");
                            this.orderForm.fileUrls.splice(index,1);
                        }
                    })

                    
                }
            });
        },
        // 上传文件成功
        handleSuccess(response, file, fileList){
            console.log(response,file, fileList,'2222');
            let fileBox = {};
            if(response.code == 200){
                this.$message.success("上传成功");
                let fileName = response.result.originalFileName;
                let fileType = fileName.substring(fileName.lastIndexOf('.')+1);
                let fileSize = file.raw.size;
                if(fileType === 'jpg' || fileType ==='png' || fileType ==='jpeg' || fileType ==='gif'){
                    this.$set(fileBox,'type',2)
                }else{
                    this.$set(fileBox,'type',1)
                }
                this.$set(fileBox,'fileName',fileName);
                this.$set(fileBox,'fileSize',fileSize)
                this.$set(fileBox,'url',response.result.absoluteUrl)
                this.orderForm.fileUrls.push(fileBox);
                console.log(this.orderForm.fileUrls,'数组');
            }

        },
        // 工单回复富文本
        changeReplyTxt(data){
            this.replyParams.describe = data;
        },
         // 上传文件尺寸
        beforeReplyAvatarUpload(file){
            console.log(file);
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!isLt5M) {
                this.$message.error('上传文件大小不能超过 5MB!');
            }
            return isLt5M;
        },
          // 文件上传超出限制
        handleReplyExceed(files, fileList){
            this.$message.warning('不能超过5个文件上传')
        },
        // 上传文件删除
        handleReplyRemove(file, fileList){
            console.log(file.response.result.absoluteUrl, fileList);
            this.replyParams.fileUrls.forEach((item,index)=>{
                if(file.response.result.absoluteUrl == item.url){
                    let params = {
                        filePath: item.url
                    }
                    deleteByFilePath(params).then(res=>{
                        console.log(res,'path');
                        if(res.code==200){
                            this.$message.success("删除成功");
                            this.replyParams.fileUrls.splice(index,1);
                        }
                    })
                }
            })
            
        },
         // 上传文件成功
        handleReplySuccess(response, file, fileList){
            let fileBox = {};
            if(response.code == 200){
                this.$message.success("上传成功");
                let fileName = response.result.originalFileName;
                let fileType = fileName.substring(fileName.lastIndexOf('.')+1);
                let fileSize = file.raw.size;
                if(fileType === 'jpg' || fileType ==='png' || fileType ==='jpeg' || fileType ==='gif'){
                    this.$set(fileBox,'type',2)
                }else{
                    this.$set(fileBox,'type',1)
                }
                this.$set(fileBox,'fileName',fileName)
                this.$set(fileBox,'fileSize',fileSize)
                this.$set(fileBox,'url',response.result.absoluteUrl)
                this.replyParams.fileUrls.push(fileBox);
                console.log(this.replyParams.fileUrls,'数组');
            }

        },
        // 点击回复
        getAnswer(id){
            this.replyParams.id = id;
            this.innerVisible = true;
        },
        // 点击确定
        getBtn(formName){
            if(this.replyParams.describe=="" && this.replyParams.fileUrls.length==0){
                this.$message.warning("描述与上传文件至少填写一项");
                return false
            }
            replyRepairOrder(this.replyParams).then(res=>{
                if(res.code == 200){
                    this.$message.success("提交成功");
                    this.$refs[formName].resetFields();
                    this.$refs.uploadFile.clearFiles();
                }
            })
            this.innerVisible = false;
            this.dialogTableVisible = false;
        },
        // 点击确定提交
        onSubmit(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    addRepairOrder(this.orderForm).then(res=>{
                        if(res.code == 200){
                            this.$message.success("提交成功");
                            this.$refs[formName].resetFields();
                            this.isShow= false;
                            this.repairOrderList();
                        }else{
                            this.$message.error("提交失败");
                        }
                    })
                   
                } else {
                    return false;
                }
            });
            

        },
        // 删除工单
        deleteOrder(id){
            deleteRepairOrder(id).then(res=>{
                if(res.code == 200){
                    this.acticleInfofile.forEach((item,index)=>{
                        if(id == item.id){
                            this.acticleInfofile.splice(index,1);
                        }
                    })
                    this.$message.success("删除成功");
                }
            })
        },
        // 删除记录工单
        deleteRecordOrder(id){
            deleteRepairOrder(id).then(res=>{
                if(res.code == 200){
                    this.acticleInfo.recordList.forEach((item,index)=>{
                        if(item.fileList != null){
                            item.fileList.forEach((val,key)=>{
                                if(id== val.id){
                                    item.fileList.splice(key,1);
                                }
                            })

                        }
                        
                    })
                    this.$message.success("删除成功");
                }
            })
        },
        // 下载工单
        getLoad(id,filename){
            let fileName = filename;
            downloadRepairOrder(id).then(res=>{
                let blob = new Blob([res], {
                    type: ''
                })
                if ('download' in document.createElement('a')) {
                    const link = document.createElement('a')
                    link.download = fileName
                    link.style.display = 'none'
                    link.href = URL.createObjectURL(blob)
                    document.body.appendChild(link)
                    link.click()
                    URL.revokeObjectURL(link.href)
                    document.body.removeChild(link)
                }
            })
            .catch((error)=>{
                console.log(error);
            })
        }
    },
    created(){
        this.repairOrderList();
        this.repairOrderType();
    },
    
}
</script>
<style lang="less" scoped>
    @import './../assets/style/edit.css';
    .work{
        width: 100%;
        .work-tit{
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

    }
    .topic{
        font-size: 16px;
        font-weight: 600;
        color: #333333;
        line-height: 22px;
        text-align: center;
        margin-bottom: 10px;
    }
    .priority{
        display: flex;
        justify-content: center;
        align-items:center;
        font-size: 14px;
        font-weight: 400;
        color: #666666;
        line-height: 20px;
        .priority-name{
            color: #333333;
            margin-right: 30px;
        }
        .sed-name{
            margin-right: 0;
        }
    }
    .tips{
        font-size: 14px;
        font-weight: 600;
        color: #333333;
        line-height: 20px;
        padding-left: 10px;
        border-left: 2px solid #1890FF;
    }
    .fromClass{
        padding: 0 20px 30px 0;
    }
    .titleClass{
        .cell{
            .title{
                color: #4370F3;
                font-size: 12px;
                font-weight: 400;
                cursor: pointer;
            }
        }
        
    }
    .person-back{
        font-size: 16px;
        font-weight: 400;
        color: #1890FF;
        display: flex;
        align-items: center;
        line-height: 40px;
        cursor: pointer;
        margin: 20px 0 0 20px;
        i{
            color:  #4370F3;
            font-size: 20px;
        }
    }
    .el-divider--horizontal{
        margin: 8px 0 20px;
    }
    .btn-box{
        text-align: center;
    }
    .concal{
        margin-right: 40px;
    }
    .descrip-tit{
        margin: 10px;
    }
    .fileSize{
        font-size: 21px;
        margin-right: 5px;
        cursor: pointer;
    }
    .unloadSize{
        font-size: 18px;
        cursor: pointer;
        margin: 0 5% 0 5px;
    }
    .delSize{
        font-size: 18px;
        color: #409eff;
        margin-left: 10px;
        cursor: pointer;
    }
    .file-upload{
        margin: 10px;
    }
    .watchFile{
        display: flex;
        font-size: 15px;
        align-items: center;
        justify-content: space-between;
        margin-top: 15px;
        cursor: pointer;
        div{
            width: 50%;
            display: flex;
            align-items: center;
            &:last-child{
                justify-content: flex-end;
            }
        }
    }
    .history-box{
        margin: 10px;
        font-size: 12px;
        font-weight: 400;
        color: #666666;
        line-height: 24px;
    }
    .history{
        margin: 10px 0 10px 15px;
    }
   .history li{
        list-style-type:decimal;
        margin-bottom: 10px;
   }
   .sumbit{
        margin: 20px 0 20px 43%;
   }
   .txt-box{
        margin-bottom: 10px;
   }
   .el-cascader{
        width: 40%;
   }
   .el-select{
        width: 40%;
   }
   .el-pagination{
    text-align: right;
    margin: 15px 0;
   }
</style>